# Kestrel: An XMPP-based Many-Task Computing Scheduler
# Author: Lance Stout <lancestout@gmail.com>
#
# Copyright 2009-2010 Clemson University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""
XMPP Roster module.

The XMPP roster module provides persistent storage of a component
agent's roster.
"""


class Roster(object):
    """
    The XMPP roster module provides persistent storage of a component
    agent's roster.

    Events listened for by this module:
      system/access/approved
      system/access/approve
      system/roster/load
      system/roster/save

    Events raised by this module:
      system/roster/loaded
      system/roster/saved
    """

    def __init__(self, kernel):
        self.roster = {}

        self.kernel = kernel
        self.events = {'system/access/approved': self.add_jid,
                       'system/access/approve': self.add_jid,
                       'system/roster/load': self.load_roster,
                       'system/roster/save': self.save_roster}
        self.kernel.register(self)

    def add_jid(self, jid):
        """
        Add a JID to the roster. The added entry is formatted
        to work with the SleekXMPP roster.
        """
        self.roster[jid] = {'in_roster': False,
                            'presence': {},
                            'name': u'',
                            'groups': [],
                            'subscription': u'both'}

    def del_jid(self, jid):
        """
        Remove a JID from the roster.
        """
        if jid in self.roster.keys():
            del self.roster[jid]

    def load_roster(self, source):
        """
        Load the roster from a file. The file will include
        each JID in the roster on a separate line.
        """
        try:
            src = open(source, 'r')
            for line in src:
                line = line.strip()
                if line:
                    self.add_jid(line)
            src.close()
        except:
            pass
        self.kernel.event('system/roster/loaded', self.roster)

    def save_roster(self, dest):
        """
        Save the roster to a file. The file will include
        each JID in the roster on a separate line.
        """
        d = open(dest, 'w+')
        for jid in roster:
            d.write(jid + '\n')
        d.close()
        self.kernel.event('system/roster/saved')
